
var vm = new Vue({
    el: '#app',
    data: function () {
        return {
            pagename: "订单管理",
            common_fn: null,
            userinfo: null,
            mainTable_maxHeight: 0,
            head: [
                { 'name': '名称', 'property': 'properties.name', 'filters': [] },
                { 'name': '创建人', 'property': 'properties.creator', 'filters': [] },
                { 'name': '创建时间', 'property': 'properties.creationdate', 'filters': [] },
                // { 'name': '描述', 'property': 'properties.description', 'filters': [] },
                { 'name': '订单号', 'property': 'properties.orderno', 'filters': [] },
                { 'name': '订单数量', 'property': 'properties.orderquantity', 'filters': [] },
                { 'name': '采购商', 'property': 'properties.customer', 'filters': [] },
                { 'name': '交付时间', 'property': 'properties.deliverydate', 'filters': [] },
                // { 'name': '优先级', 'property': 'properties.priority', 'filters': [] },
                // { 'name': '发布状态', 'property': 'properties.state_name', 'filters': [] },
            ],
            //保存订单等待框
            fullscreenLoading: false,
            //选中产品的snapshotId
            snapshotId_PBom2MBom: 0,
            // 订单列表
            data: [],
            //删除订单
            deleteOrderDialog: false,
            deleteOrderIndex: 0,
            deleteOrder: "",
            // 选中的订单
            orderChecked: null,
            addDialog: false,
            detailmsgDialog: false,
            loading: false,
            formLabelWidth: '80px',
            searchType: true,
            // 查询参数
            search: {
                orderno: ''
            },
            // 加载条件  默认 未发布
            filter: '未发布',
            addCurrent: {
                name: '',
                productName: '',     //生产产品，从快速工艺来，原批次计划选，挪到新建订单
                description: '',
                customer: '',
                deliverydate: '',
                priority: '',
                orderquantity: '',   //订单数量，即批次计划中的批次计划数量，原批次计划选，挪到新建订单
                orderno: '',
            },
            addCurrentRules: {
                orderno: [
                    { required: true, message: '请输入订单号', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '请输入订单名称', trigger: 'blur' },
                ],
                productName: [
                    { required: true, message: '请输入产品名称', trigger: 'change' },
                ],
                deliverydate: [
                    { required: true, message: '请输入订单号', trigger: 'change' },
                ],
                orderquantity: [
                    { required: true, message: '请输入订单数量', trigger: 'blur' },
                    { type: 'number', message: '数量必须为数字值' }
                ],
            },
            //产品 从快速工艺获取 
            productTree: [],
            productTreeDialog: false,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            productSelected: "",
            // 产品组成列表
            sfDate: [],
            looksfDate: [],
            // 权限
            right: {
                modify: false,
                remove: false,
                create: false
            },
            //分页-----------------
            // 总数量
            totalnum: 0,
            // 总页数
            totalpage: 0,
            // 每页数量
            everypagenum: 20,
            // 当前页
            currentpage: 1,
            //当前页数据
            currentData: [],
            //人员组件信息
            currentComponent: '',
            currentComponentObj: null,
            // 打印模板HTML
            sfDataPrintHtml: '',
            //For APP
            deliverydateInit: '',
        }
    },
    methods: {
        //过滤订单
        getDataFilter: function (filter) {
            this.filter = filter;
            this.getData()
        },
        // 获取所有订单
        getData: function () {
            var self = this;
            var filters = [];
            console.log(self.filter)
            if (self.filter == '未发布') {
                filters.push({
                    "classFlag": 1,
                    "classType": "MesOrderSheet",
                    "propName": "state",
                    "op": 4,
                    "propValue": "0",
                    "propValue2": "",
                    "logic": 0,
                    "leftSplitter": 0,
                    "rightSplitter": 0,
                    "bAddWhereClauseFlag": true
                })
            }
            if (self.filter == '已发布') {
                filters.push({
                    "classFlag": 1,
                    "classType": "MesOrderSheet",
                    "propName": "state",
                    "op": 5,
                    "propValue": "0",
                    "propValue2": "",
                    "logic": 0,
                    "leftSplitter": 0,
                    "rightSplitter": 0,
                    "bAddWhereClauseFlag": true
                })
            }
            if (self.searchType) {
                if (self.search.orderno != '') {
                    filters.push({
                        "classFlag": 1,
                        "classType": "MesOrderSheet",
                        "propName": "orderno",
                        "op": 7,
                        "propValue": self.search.orderno,
                        "propValue2": "",
                        "logic": 0,
                        "leftSplitter": 0,
                        "rightSplitter": 0,
                        "bAddWhereClauseFlag": true
                    })
                }
            }
            self.loading = true;
            self.common_fn.queryObject("MesOrderSheet", filters, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    for (i = response.result.length - 1; i >= 0; i--) {
                        response.result[i].properties.state == 0 ? response.result[i].properties['state_name'] = '待审核' : response.result[i].properties.state == 1 ? response.result[i].properties['state_name'] = '审核中' : response.result[i].properties['state_name'] = '已发布';
                        response.result[i].properties.deliverydate = response.result[i].properties.deliverydate.split(' ')[0];
                        response.result[i].properties.creationdate = response.result[i].properties.creationdate.split(' ')[0]; //APP加
                        response.result[i].properties.orderquantity = Number(response.result[i].properties.orderquantity);
                    }
                    self.data = response.result;
                    self.totalnum = response.result.length;
                    self.totalpage = Math.ceil(response.result.length / self.everypagenum);
                    self.currentData = self.data.slice(0, self.totalnum > self.everypagenum ? self.everypagenum : self.totalnum);
                    pushFilterData('head', self.head, self.currentData);
                } else {
                    notify(response.errMsg, 'error')
                }
                self.loading = false;
            })
        },
        // 加载上一页或下一页
        handleCurrentChange: function (num) {
            var self = this;
            self.currentpage = num;
            self.currentData = self.data.slice((num - 1) * self.everypagenum, num == self.totalpage ? self.totalnum : (self.everypagenum * num));
        },
        // 新增订单
        addorder: function () {
            if (!this.right.create) {
                this.$message.error('没有新增权限'); return
            }
            this.clearTemplateOrder();
            this.sfDate = [];
            this.addDialog = true;
            this.orderChecked = {
                id: 0,
                properties: {},
                type: 'MesOrderSheet'
            }
        },
        // 编辑订单
        edit: function (row) {
            var self = this;
            if (!self.right.modify) {
                message('没有编辑权限', 'error'); return
            }
            self.clearTemplateOrder();
            self.sfDate = [];
            if (row.sfDate) { delete row.sfDate }
            self.orderChecked = row;
            for (var key in self.addCurrent) {

                self.addCurrent[key] = self.orderChecked.properties[key];
            }
            this.addDialog = true;
        },
        // 保存订单
        saveOrder: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.addCurrent.orderquantity == 0) {
                        message('订单数量不能为0', 'error'); return
                    } else {
                        var self = this;
                        self.fullscreenLoading = true;
                        var ordersheetObj = self.orderChecked;
                        var productFormationObj = self.sfDate;
                        for (var key in self.addCurrent) {
                            ordersheetObj.properties[key] = self.addCurrent[key];
                        }
                        var param = {
                            "ordersheetObj": ordersheetObj,
                            "prdFormationObj": productFormationObj,
                            "addOrModifyObj": ordersheetObj.id == 0 ? true : false
                        }
                        self.common_fn.invoke("JridgeMesSTD_AdditionalService.dll", "JridgeMesSTD_AdditionalService.OrderSheetMgr", "OrderSheetSave", param, self.userinfo, function (response) {
                            if (response.resFlag == 0) {
                                ///////////建立订单后，即做批次计划，批次计划数量与订单数量相同
                                //（1）获取产品相关的信息：产品编号、物料编码、图号
                                //(2)新建批次计划
                                //(3)PBOM转MBOM
                                //批次计划开始和结束时间默认当天
                                var newOrder = response.result;  //本次创建的订单
                                //（1）获取产品相关的信息：产品编号、物料编码、图号
                                self.common_fn_school.QueryRelatedGraphNode(self.productSelected.id, "PlmProduct", "QcpProductWithAssmebly", function (response) {
                                    if (response.resFlag == 0) {
                                        //获取总装ID，为PBOM转BOM准备
                                        var part_objids = response.result[0].entity.id;
                                        var materialno_part = response.result[0].entity.properties.materialno;
                                        var indentityno_part = response.result[0].entity.properties.identityno
                                        var d = new Date(self.addCurrent.deliverydate)
                                        var newProductionSchedule = {
                                            "id": 0,
                                            "properties": {
                                                "name": self.productSelected.name,
                                                "topassembly_objid": self.productSelected.id,
                                                "productno": self.productSelected.name,
                                                "lotnum": self.addCurrent.orderquantity,
                                                "lotno": self.addCurrent.orderno + "-0001",
                                                "materialno": materialno_part,
                                                "indentityno": indentityno_part,
                                                "deliverydate": d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
                                            },
                                            "type": "MESPRODUCTIONSCHEDULE"
                                        }
                                        //(2)新建批次计划
                                        self.common_fn_school.CreateProductionSchedule(newOrder, newProductionSchedule, function (response) {
                                            if (response.resFlag == 0) {
                                                //(3)PBOM转MBOM
                                                //获取批次计划，为PBOM转BOM准备
                                                var producttionSchedule__PBom2MBom = response.result;
                                                //将总装ID添入批次计划
                                                producttionSchedule__PBom2MBom.properties.part_objids = part_objids;
                                                //获取选中产品的snaphost，为PBOM转BOM准备
                                                self.common_fn_school.GetCurrentSnapshot(self.productSelected.entity.id, self.productSelected.entity.type, 2, function (response) {
                                                    if (response.resFlag == 0) {
                                                        self.snapshotId_PBom2MBom = response.result.id
                                                        var order__PBom2MBom = self.productSelected.entity;
                                                        //开始转换
                                                        self.common_fn_school.PBom2MBomDirectly(order__PBom2MBom, producttionSchedule__PBom2MBom, self.snapshotId_PBom2MBom, function (response) {
                                                            if (response.resFlag == 0) {
                                                                self.fullscreenLoading = false;
                                                                message('订单新建成功！', 'success')
                                                                self.addDialog = false;  //关闭新建订单对话框
                                                                self.getData();  //刷新数据
                                                            }
                                                        })
                                                    }
                                                })
                                            }
                                        })
                                    }
                                })
                            } else {
                                notify(response.errMsg, 'error')
                            }
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        delDialog: function (index, data) {
            this.deleteOrderDialog = true;
            this.deleteOrderIndex = index;
            this.deleteOrder = data;
        },

        // 删除订单 或 产品组成
        del: function () {
            var self = this;
            if (!self.right.remove) {
                message('没有删除权限', 'error'); return
            }
            var param = {
                "ordersheetObj": {},
                "prdFormationObj": {}
            }
            var str = self.deleteOrder[self.deleteOrderIndex].type.toLocaleLowerCase();
            if (str == 'mesordersheet') {
                param.ordersheetObj = self.deleteOrder[self.deleteOrderIndex];
            } else {
                param.prdFormationObj = self.deleteOrder[self.deleteOrderIndex];
                if (param.prdFormationObj.id == 0) {
                    self.deleteOrder.splice(self.deleteOrderIndex, 1); return
                }
            }
            self.common_fn.invoke("JridgeMesSTD_AdditionalService.dll", "JridgeMesSTD_AdditionalService.OrderSheetMgr", "DeleteObject", param, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    if (str == 'mesordersheet') {
                        self.getData();
                        self.addDialog = false;
                    }
                    self.deleteOrder.splice(self.deleteOrderIndex, 1);
                    self.deleteOrderDialog = false;
                    message('成功删除订单', 'success');
                } else {
                    notify(response.errMsg, 'error')
                }
            })
        },
        // 清空当前数据
        clearTemplateOrder: function () {
            this.addCurrent = {
                name: '',
                description: '',
                customer: '',
                deliverydate: '',
                priority: '',
                orderquantity: '',
                orderno: '',

            }
        },

        //点击触发产品选择器
        clickToSelProduct: function () {
            var self = this;
            //获取根节点
            var param = {
                "appName": "mes",
                "sql": "select * from PLM_PRODUCTCLASSHIERARCHY where A_OBJID=0"
            };
            self.common_fn.sqlFn(param, function (response) {
                if (response.resFlag == 0) {
                    if (response.result.length !== 0) {
                        var entryObjects = []
                        for (let i = 0; i < response.result.length; i++) {
                            entryObjects = [{
                                "id": parseInt(response.result[i].properties.lobjid),
                                "type": "PlmProductClassification"
                            }];
                        }
                        //获取产品大类下的相关产品
                        self.common_fn_school.QueryObjectsGraph(self.userinfo.user, null, entryObjects, ["PlmProductClassHierarchy", "PlmProductClassProduct"], function (response) {
                            if (response.resFlag == 0) {
                                self.productTree = []
                                self.getProductTree(response.result.roots);
                                self.productTreeDialog = true;
                            }
                        })
                    } else {
                        notify("请您先新建产品！", "warning")
                    }
                } else {
                    notify(response.errMsg, 'error')
                }
            })
        },

        //递归循环获得产品大类及产品树结构
        getProductTree: function (target) {
            let self = this;
            target.forEach(function (item) {
                item.id = item.entity.id;
                item.name = item.entity.properties.name;
                item.identityno = item.entity.properties.identityno;  //产品编号
                item.type = item.entity.type;
                if (item.children.length > 0) {
                    self.getProductTree(item.children)
                }
            });
            self.productTree = target
        },

        //选中某一个产品
        handleProductNodeClick(data) {
            this.productSelected = data
        },

        //确认选中的产品
        confirmProductSelected: function () {
            console.log(this.productSelected)
            if (this.productSelected.type !== "PlmProduct") {
                notify("注意：请选择一个产品，并非产品大类", 'warning')
            } else {
                this.productTreeDialog = false;
                this.addCurrent.productName = this.productSelected.name
            }
        },

        //点击触发人员选择器
        clickToOpenPeopleSelComponent: function (str) {
            var self = this;
            self.currentComponent = '';
            window.setTimeout(function () {
                self.currentComponent = 'people-sel-mul';
                self.currentComponentObj = {
                    targetdataname: 'addCurrent',
                    index: null,
                    key: str,
                    str: self.addCurrent.drawreceiver
                };
            }, 200)
        },

        // 启动流程
        startFlow: function (index, data) {
            var self = this;
            var param = {
                user: self.userinfo.user,
                wf_templateID: '003',
                wf_templateName: '订单审批流程',
                wf_fID: '0',
                title: data[index].properties.companyno + data[index].properties.name + '',
                wf_nextnodeID: '306',
                wf_nexthandler: '0405040169',  //周军
                wf_nextnodename: '编制',
                associated_objects: [data[index]],
                accepters: {}
            }
            self.common_fn.XHR_post('../workflow/StartTask', param, function (response) {
                if (response.data.resFlag == 0) {
                    message('启动流程成功', 'success')
                    var param1 = {
                        storageable: {
                            id: Number(data[index].id),
                            properties: {
                                state: 1
                            },
                            type: "MesOrderSheet"
                        }
                    }
                    self.common_fn.invokeFun('Update', param1, self.userinfo, function (res1) {
                        if (res1.resFlag == 0) {
                            data[index].properties.state = 1;
                            self.data = JSON.parse(JSON.stringify(data));
                        } else {
                            notify(res1.errMsg, 'error')
                        }
                    })
                } else {
                    notify(response.errMsg, 'error')
                }
            })
        },
        // 查看订单详细信息
        look: function (row) {
            var self = this;
            self.orderChecked = row;
            self.detailmsgDialog = true;
        },
        //取消发布
        cancel: function (index, data) {
            var self = this;
            var param = {
                "appName": "mes",
                "sql": "update mes_ordersheet set state = 0 where objid ='" + data[index].id + "'"
            };
            var r = confirm('确定取消发布吗？')
            if (r) {
                self.common_fn.sqlFn(param, function (response) {
                    if (response.resFlag == 0) {
                        data[index].properties.state = 0;
                        self.getData();
                    } else {
                        notify(response.errMsg, 'error')
                    }
                })
            }
        },
        //For APP
        openPicker() {
            this.$refs.picker.open();
        },
        //For APP  格式化时间
        formateDate: function (date) {
            this.addCurrent.deliverydate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
        }
    },
    mounted: function () {
        var self = this;
        self.common_fn = new common_fn();
        self.common_fn_school = new common_fn_school();
        self.common_fn.init(function () {
            self.common_fn.UserInfo(function (response) {
                if (response.user == null) {
                    window.location.href = 'login.html?redirect=addorder.html';
                }
                self.userinfo = response;
                self.common_fn.CheckFunction(self.userinfo, 'mes', 'mes', 'OrderMgr', '', '', 'addorder', function () { })
                // 修改权限
                self.common_fn.CheckFunction(self.userinfo.user, 'mes', 'mes', 'OrderMgr', 'Base', 'Modify', null, function (res) {
                    if (res == 1) { self.right.modify = true }
                })
                // 删除权限
                self.common_fn.CheckFunction(self.userinfo.user, 'mes', 'mes', 'OrderMgr', 'Base', 'Remove', null, function (res) {
                    if (res == 1) { self.right.remove = true }
                })
                // 新增权限
                self.common_fn.CheckFunction(self.userinfo.user, 'mes', 'mes', 'OrderMgr', 'Base', 'Create', null, function (res) {
                    if (res == 1) { self.right.create = true }
                })
                self.getData();

            })
        });
        bus.$on('retselpeople', function (data) {
            var str = '';
            for (var i = 0; i < data.result.length; i++) {
                str += data.result[i].properties.name + ',';
            }
            str = str.substring(0, str.length - 1);
            self.addCurrent.drawreceiver = str;
        })
    }
})
window.onload = function () {
    if (vm.mainTable_maxHeight != null || vm.mainTable_maxHeight != undefined) {
        window.setTimeout(function () {
            vm.mainTable_maxHeight = $(window).height() - 150;
        }, 100)
    }
}
